package com.university.evaluation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.university.evaluation.entity.EvaluationSystem;
import com.university.evaluation.mapper.EvaluationSystemMapper;
import com.university.evaluation.service.EvaluationSystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EvaluationSystemServiceImpl extends ServiceImpl<EvaluationSystemMapper, EvaluationSystem> implements EvaluationSystemService {

    @Autowired
    private EvaluationSystemMapper evaluationSystemMapper;

    @Override
    public EvaluationSystem getCurrentSystem() {
        return evaluationSystemMapper.findCurrentSystem();
    }

    @Override
    public EvaluationSystem findByAcademicYearAndSemester(String academicYear, Integer semester) {
        QueryWrapper<EvaluationSystem> wrapper = new QueryWrapper<>();
        wrapper.eq("academic_year", academicYear)
               .eq("semester", semester);
        return getOne(wrapper);
    }

    @Override
    public List<EvaluationSystem> findAll(int pageNum, int pageSize) {
        Page<EvaluationSystem> page = new Page<>(pageNum, pageSize);
        return page(page).getRecords();
    }

    @Override
    public boolean enableSystem(Long systemId) {
        // 先禁用所有其他启用中的测评体系
        QueryWrapper<EvaluationSystem> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1); // 1表示启用中
        List<EvaluationSystem> activeSystems = list(wrapper);
        for (EvaluationSystem system : activeSystems) {
            system.setStatus(0); // 0表示未启用
            updateById(system);
        }
        
        // 启用当前测评体系
        EvaluationSystem system = getById(systemId);
        if (system != null) {
            system.setStatus(1); // 1表示启用中
            system.setStartTime(LocalDateTime.now());
            return updateById(system);
        }
        return false;
    }

    @Override
    public boolean closeSystem(Long systemId) {
        EvaluationSystem system = getById(systemId);
        if (system != null) {
            system.setStatus(2); // 2表示已结束
            system.setEndTime(LocalDateTime.now());
            return updateById(system);
        }
        return false;
    }

}